from influxdb import InfluxDBClient
import argparse
import pandas as pd


class influxdbHelper:
    def __init__(self):
        self.host = '192.168.3.108'
        self.client = InfluxDBClient(self.host, 8086, '')

    def createtest():

        client = InfluxDBClient(self.host, 8086, '')  # 连接数据库
        client.create_database('example')  # 创建数据库

        points = [  # 待写入数据库的点组成的列表
            {
                "measurement": "cpu_load_short",
                "tags": {
                    "host": "server01",
                    "region": "us-west"
                },
                "time": "2009-11-10T23:00:00Z",
                "fields": {
                    "value": 0.64
                }
            }
        ]
        client.write_points(points, database='example')  # 将这些点写入指定database
        # 查询刚刚写入的点
        result = client.query('select value from cpu_load_short;',
                              database='example')
        print(result)

    '''
        print("创建数据库: " + dbname)
        client.create_database(dbname)

        print("创建retention策略")
        client.create_retention_policy('awesome_policy', '3d', 3, default=True)

        print("切换用户: " + dbuser)
        client.switch_user(dbuser, dbuser_password)

        print("写入points: {0}".format(json_body))
        client.write_points(json_body)

        print("查询数据: " + query)
        result = client.query(query)

        print("结果: {0}".format(result))

        print("查询data: " + query_where)
        result = client.query(query_where, bind_params=bind_params)

        print("结果: {0}".format(result))

        print("切换用户: " + user)
        client.switch_user(user, password)

        print("删除数据库: " + dbname)
        client.drop_database(dbname)
'''

    def parse_args():
        """解析args"""
        parser = argparse.ArgumentParser(
            description='example code to play with InfluxDB')
        parser.add_argument('--host',
                            type=str,
                            required=False,
                            default='localhost',
                            help='hostname of InfluxDB http API')
        parser.add_argument('--port',
                            type=int,
                            required=False,
                            default=8086,
                            help='port of InfluxDB http API')
        return parser.parse_args()

    def get_kline(self):
        result = self.client.query(
            "select * from KlineDay where symbol = 'HSI'",
            database='KlineIndex')

        return result.get_points()

    def get_klines(self, sql, dbname):
        result = self.client.query(sql, database=dbname)
        df = pd.DataFrame(result.get_points())
        df['time'] = pd.to_datetime(df['time'])
        df = df.set_index('time')
        return df
